import json
import re
import sys
import os

from pyquery import PyQuery as pq

from formatContent import formatContent, filterAttributes, filterTag
from requestUrl import getDocByUrl
from logs import saveLog

# url = 'https://mp.weixin.qq.com/s/7DLebdDmldtE08rnoZIROw'

try:
    urlQuery = '?' + sys.argv[2]
    env = sys.argv[3]
except:
    urlQuery = ''
    env = sys.argv[2]
# 要获取内容的URL
url = sys.argv[1] + urlQuery

# 获取html文本doc，得到pq对象
doc = getDocByUrl(url=url)

# 标题
title = re.findall("<meta.*?property=\"og:title\" content=\"([^\"]+)\"/>", doc.html())[0]

# 封面图
coverUrl = re.findall("<meta.*?property=\"og:image\" content=\"([^\"]+)\"/>", doc.html())[0]

# 原创标识
isOriginal = False
if doc('#copyright_logo'):
    isOriginal = True

# 文章作者
authorName = ''
# 已下为公众号名称
if doc('.original_primary_nickname'):
    authorName = doc('.original_primary_nickname').text()
if doc('#js_author_name'):
    authorName = doc('#js_author_name').text()
if doc('#js_name'):
    authorName = doc('#js_name').text()
accountName = authorName
# 原创作者名称
if doc('.rich_media_meta_text'):
    authorName = doc('.rich_media_meta_text').text()

# 时间：Y-m-d H:M:S
publicTime = 0
for script in doc('script'):
    if doc(script).text().find('publish_time') >= 0:
        for item in doc(script).text().split(';'):
            if item.strip().find('var t') >= 0:
                publicTime = item.strip().split('\"')[3]

# 文章正文
if doc('#img_list'):  # 正文只有图片
    articleContent = pq("<div id='img'>" + doc('#img_list').html().replace('&#13;', '').strip() + "</div>")
    articleContent = articleContent('#img')
elif doc('#js_content'):  # 正文包含各种内容
    title = doc('#activity-name').html().replace(u'\xa0', u'').replace('\n', '').replace('\t', '').replace(' ', '')
    articleContent = doc('#js_content')

# 去【李世泉】那里过滤标签
content = formatContent(articleContent.html(), isRemoveSrcParams=True, env=env)

result = {
    'not_format_content': articleContent.html(),
    'content': content,
    'author_name': authorName,
    'account_name': accountName,
    'cover_url': coverUrl,
    'public_time': publicTime,
    'description': '',
    'title': title,
}
logData = {
    'params': sys.argv,
    'content': articleContent.html(),
    'format_content': content,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False))
